(function () {
    var calendar = {
        curDate: new Date(),
        holidays: ['假期安排', '元旦节', '除夕', '春节', '清明节', '劳动节', '端午节', '中秋节', '国庆节'],

        init() {
            //下拉列表
            this.renderSelect(this.curDate)
            this.getData(this.curDate)
        },
        renderSelect(d) {
            var dayz = document.querySelector('.right .date')
            var day = document.querySelector('.right .day')
            var yearList = document.querySelector('.yearSelect .selectBox ul')
            var monthList = document.querySelector('.montSelect .selectBox ul')
            var holidatList = document.querySelector('.holidaySelect .selectBox ul')
            var yearSelected = document.querySelector('.yearSelect .selected span')
            var monthSelected = document.querySelector('.montSelect .selected span')
            var holidaySelected = document.querySelector('.holidaySelect .selected span')
            let li = '';
            yearList.innerHTML = '';
            for (var i = 1900; i <= 2050; i++) {
                li += `<li ${i == d.getFullYear() ? 'class="active"' : ''}>${i}年</li>`
            }
            yearList.innerHTML = li
            // 生成年份
            yearSelected.innerHTML = d.getFullYear() + '年'
            //月份
            let month = ''
            monthList.innerHTML = ''
            for (var i = 1; i <= 12; i++) {
                month += `<li ${i == (d.getMonth() + 1) ? 'class="active"' : ''}>${i}月</li>`
            }
            monthList.innerHTML = month
            monthSelected.innerHTML = d.getMonth() ? getMonth() : 1 + '月'
            //日期
            let dyz = `${d.getFullYear()}-${d.getMonth() ? d.getMonth() : '01'}-${d.getDate()}`
            day.innerHTML = d.getDate()
            dayz.innerHTML = dyz
            //假期
            let holi = ''
            holidatList.innerHTML = ''
            for (var i = 0; i < this.holidays.length; i++) {
                holi += `<li ${i == 0 ? 'class="active"' : ''}>${this.holidays[i]}</li>`
            }
            holidatList.innerHTML = holi
            holidaySelected.innerHTML = this.holidays[0]
            //返回今天
            var navreturn = document.querySelector('button')
            navreturn.onclick = () => {
                let d = new Date()
                yearSelected.innerHTML = d.getFullYear() + '年'
                monthSelected.innerHTML = d.getMonth() ? getMonth() : 1 + '月'
                this.getData(d)
                var selects = document.querySelectorAll('.select .selectBox ul li')
                let select = [...selects]
                select.forEach((item, index) => {
                    item.classList.remove('active')
                })
            }
            this.selectBingdEvent()
        },
        //清除选中样式
        closeSelect() {
            var selects = document.querySelectorAll('.select')
            let select = [...selects]
            let open = select.find(item => item.classList.contains('active'))
            open && open.classList.remove('active')
        },
        //日期下拉框
        selectBingdEvent() {
            var selects = document.querySelectorAll('.select')
            selects.forEach((item, index) => {
                let cl = item.classList
                var li = item.querySelector('span')
                item.onclick = ev => {
                    if (cl.contains('active')) {
                        cl.remove('active')
                    } else {
                        this.closeSelect()
                        cl.add('active')
                        this.scrollBar()
                    }
                    // 处理点的不是列表
                    if (ev.target.tagName != 'LI') return
                    var select = [...item.querySelectorAll('ul li')]
                    select.find(item => item.classList.contains('active')).classList.remove('active')
                    ev.target.classList.add('active')
                    switch (index) {
                        case 0:
                            this.curDate.setFullYear(parseInt(ev.target.innerHTML))
                            li.innerHTML = ev.target.innerHTML
                            break
                        case 1:
                            this.curDate.setMonth(parseInt(ev.target.innerHTML) - 1)
                            li.innerHTML = ev.target.innerHTML
                            break
                        case 2:
                            li.innerHTML = ev.target.innerHTML
                    }
                    this.getData(this.curDate)
                }
            })
        },
        //滚动条事件
        scrollBar() {
            var scrollWrap = document.querySelector('.yearSelect .selectBox')
            var content = document.querySelector('.yearSelect .selectBox ul')
            var barWrap = document.querySelector('.yearSelect .selectBox .scroll')
            // 滚动滑块
            var bar = document.querySelector('.yearSelect .selectBox span')
            // 初始化
            bar.style.transform = content.style.transform = 'translateY(0)'
            //设置滚动高度
            var multiple = (content.offsetHeight + 18) / scrollWrap.offsetHeight
            multiple = multiple > 20 ? 20 : multiple
            bar.style.height = scrollWrap.offsetHeight / multiple + 'px'
            //滑块拖拽
            var scrollTop = 0 //滚动条走的距离
            var maxHeight = barWrap.offsetHeight - bar.offsetHeight //滑块能走的最大距离
            bar.onmousedown = function (ev) {
                var startY = ev.clientY
                var startT = parseInt(this.style.transform.split('(')[1])
                bar.style.transition = content.style.transition = null
                document.onmousemove = ev => {
                    scrollTop = ev.clientY - startY + startT
                    scroll()
                }
                document.onmouseup = () => document.onmousemove = null
            }
            barWrap.onclick = (ev) => ev.stopPropagation
            function scroll() {
                if (scrollTop < 0) {
                    scrollTop = 0
                }
                if (scrollTop > maxHeight) {
                    scrollTop = maxHeight
                }
                var scaleY = scrollTop / maxHeight
                bar.style.transform = 'translateY(' + scrollTop + 'px)'
                content.style.transform = 'translateY(' + (scrollWrap.offsetHeight - content.offsetHeight - 18) * scaleY + 'px)'
            }
            scrollWrap.onwheel = (ev) => {
                ev.deltaY > 0 ? scrollTop += 10 : scrollTop -= 10
                bar.style.transition = content.style.transition = '.2s'
                scroll()
                ev.preventDefault()
            }
        },
        //请求数据
        getData(d) {
            $.ajax({
                url: `https://www.rili.com.cn/rili/json/pc_wnl/${d.getFullYear()}/${d.getMonth() + 1}.js`,
                dataType: 'jsonp',
                success(res) {
                }

            })
            window.jsonrun_PcWnl = (data) => {
                console.log(data)
                this.renderDate(d, data.data)
            }
        },
        //获取某月的最后一天日期:日传0即可返回这个月有多少天
        getEndDay: (year, month) => new Date(year, month, 0).getDate(),
        // 获取某月的第一天是周几
        getFirstWeek: (year, month) => new Date(year, month - 1, 1).getDay(),
        delTag: str => str.replace(/<\/?.+?\/?>/g, ''),
        renderDate(e, data) {
            console.log(e)
            var tbody = document.querySelector('.dateWrap tbody')
            var lastEndDay = this.getEndDay(e.getFullYear(), e.getMonth()) //上个月的最后一天，月份不需要计算
            var curEdnDay = this.getEndDay(e.getFullYear(), e.getMonth() + 1) // 当前月的最后一天，月份+1
            var week = this.getFirstWeek(e.getFullYear(), e.getMonth() + 1) //当前月第一天周几,可以通过某月的第一天的星期来判断需要显示几个上个月，例如当前月第一天是周六，那就显示5个上个月日期
            var lastDateNum = week - 1
            lastDateNum = week == 0 ? 6 : week //当前月第一天为周日week就为0，就需要为上个月空6位。
            var prevStartDate = lastEndDay - lastDateNum//上个月的起始日期,这个值少了1，是因为最后一天的各自它减去了
            var nextStartDate = 1//下个月起始
            var curStartDate = 1//当前月起始
            console.log('prevStartDate', prevStartDate)
            var cn = -1
            console.log(lastEndDay, curEdnDay, week)
            tbody.innerHTML = ''
            for (var i = 0; i < 6; i++) { //tr
                var tr = document.createElement('tr')
                var td = ''
                for (var j = 0; j < 7; j++) {//td
                    cn++
                    var festival = data[cn].jie ? this.delTag(data[cn].jie) : data[cn].r2
                    var weekday = data[cn].jia == 90 ? 'weekady' : ''//班
                    var holiday = data[cn].jia > 90 ? 'holiday' : ''//休
                    if (cn < lastDateNum) {
                        //上个月日期，lastDateNum代表的是显示上个月的数量，cn小于<lastDateNum就是渲染多少个
                        td += `<td>
                        <div class="prevMonth ${weekday + ' ' + holiday}">
                        <span>${++prevStartDate}</span>
                        <span>${festival}</span>
                        </div>
                        </td>`
                    } else if (cn >= lastDateNum + curEdnDay) {
                        //下个月
                        td += `<td>
                        <div class="nextMonth ${weekday + ' ' + holiday}">
                        <span>${nextStartDate++}</span>
                        <span>${festival}</span>
                        </div>
                        </td>`
                    } else {
                        //当前
                        var cl = ''
                        if (curStartDate == e.getDate() && e.getFullYear() == new Date().getFullYear() && new Date().getMonth() == e.getMonth()) {
                            cl = 'today'
                        }
                        if (new Date().getFullYear() == e.getFullYear() &&
                            new Date().getMonth() == e.getMonth() &&
                            new Date().getDate() == e.getDate() == curStartDate
                        ) {
                            cl = 'active'
                        }
                        td += `<td>
                        <div class="${cl + ' ' + weekday + ' ' + holiday}">
                        <span>${curStartDate++}</span>
                        <span>${festival}</span>
                        </div>
                        </td>`
                    }
                    tr.innerHTML = td
                }
                tbody.appendChild(tr)
            }
        }
    }
    calendar.init()
})();